import { createSlice } from "@reduxjs/toolkit"; 
import axios from "axios";

const takeawaySlice = createSlice({
  name: "takeaway",
  initialState: {
    foodsList: [],
    activeIndex: 0,
    cartList: [],
    isVisible: false
  },
  reducers: {
    setFoodsList: (state, action) => {
      state.foodsList = action.payload;
    },
    setActiveIndex: (state, action) => {
      state.activeIndex = action.payload;
    },
    addCartList(state, action) {
      let data = state.cartList.find(item => item.id === action.payload.id);
      if (data) {
        data.count += 1;
      } else {
        state.cartList.push(action.payload);
      } 
    },
    subCartList(state, action){
      if (action.payload.type === 'all') {
        state.cartList = [];
        state.isVisible = false;
        return 
      }
      let index = state.cartList.findIndex(item => item.id === action.payload.id);
      if (action.payload.count === 0) {
        state.cartList.splice(index, 1);
        state.isVisible = state.cartList.length !== 0
      }else{
        state.cartList[index].count  = action.payload.count
      }
    },
    setIsVisible(state, action) {
      state.isVisible = action.payload;
    }
  },
})
const { setFoodsList, setActiveIndex, addCartList ,subCartList ,setIsVisible} = takeawaySlice.actions;
const takeawayReducer = takeawaySlice.reducer;
const getFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    console.log(res.data);
    dispatch(setFoodsList(res.data));
  }
}
export { getFoodsList, setActiveIndex, addCartList ,subCartList ,setIsVisible};
export default takeawayReducer;